<!--
 * @页面名称:账号管理
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="card account">
    <el-space style="width: 100%; margin-bottom: 8px">
      <el-button :disabled="BtnStatus[0]" type="primary" @click="add">新增</el-button>
      <el-button :disabled="BtnStatus[1]" @click="edit">修改</el-button>
      <el-button :disabled="BtnStatus[2]" type="danger" @click="del">删除</el-button>
      <el-button :disabled="BtnStatus[3]" type="" @click="updataPWD">修改密码</el-button>
      <el-input
        style="width: 20vw"
        @input="onSearchChange"
        v-model="searchVal"
        placeholder="请输入用户名关键字进行搜索"
      ></el-input>
    </el-space>
    <div style="height: calc(100% - 60px)">
      <stable :columns="tableSetting.columns" :data="tableSetting.data" @rowClick="rowClick"></stable>
    </div>
    <!-- 弹出框 -->
    <el-dialog v-model="dialogSetting.visible" :title="dialogSetting.title" width="45%" draggable>
      <el-form label-width="90px" :model="formData" :rules="rules" ref="formRef">
        <div class="line">
          <el-form-item label="顺序号:" prop="U_Order">
            <el-input v-model="formData.U_Order"></el-input>
          </el-form-item>
          <el-form-item label="用户名:" prop="U_Name">
            <el-input v-model="formData.U_Name"></el-input>
          </el-form-item>
        </div>
        <div class="line">
          <el-form-item label="密码:" prop="U_PWD" v-if="dialogSetting.title === '新增'">
            <el-input show-password v-model="formData.U_PWD"></el-input>
          </el-form-item>
          <el-form-item label="员工名称:" prop="U_CName">
            <el-input v-model="formData.U_CName"></el-input>
          </el-form-item>
        </div>
        <div class="line">
          <el-form-item label="绑定MAC:" prop="U_Binding_MAC">
            <el-input v-model="formData.U_Binding_MAC"></el-input>
          </el-form-item>
          <el-form-item label="绑定IP:" prop="U_Binding_IP">
            <el-input v-model="formData.U_Binding_IP"></el-input>
          </el-form-item>
        </div>
        <div class="line">
          <el-form-item label="邮箱:" prop="U_Email">
            <el-input v-model="formData.U_Email"></el-input>
          </el-form-item>
          <el-form-item label="手机号:" prop="U_Mobile_Num">
            <el-input v-model="formData.U_Mobile_Num"></el-input>
          </el-form-item>
        </div>
        <div class="line">
          <el-form-item label="认证路径:" prop="U_CertPath">
            <el-input v-model="formData.U_CertPath"></el-input>
          </el-form-item>
          <el-form-item label="官方号:" prop="U_Office_Phone">
            <el-input v-model="formData.U_Office_Phone"></el-input>
          </el-form-item>
        </div>
        <el-form-item label="角色名称:">
          <el-select v-model="relevanceData" multiple @change="roleChange">
            <el-option v-for="item in allRoleData" :key="item.G_ID" :label="item.G_Name" :value="item.G_ID" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期:" prop="U_Validity_Time" style="width: 100%">
          <el-date-picker
            class="datePick"
            :clearable="false"
            v-model="formData.U_Validity_Time"
            type="date"
            placeholder="请选择日期"
          />
        </el-form-item>
        <el-form-item v-if="dialogSetting.title === '修改'" label="错误次数:" prop="U_PasswordErrCount">
          <el-input type="number" v-model="formData.U_PasswordErrCount"></el-input>
        </el-form-item>
        <el-row class="check-group">
          <el-col :span="4.8">
            <el-form-item label="管理员:" prop="U_IsAdministrator">
              <el-checkbox v-model="formData.U_IsAdministrator"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="超级管理员:" prop="U_IsSuperAdministrator">
              <el-checkbox v-model="formData.U_IsSuperAdministrator"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="是否启用:" prop="U_Enable">
              <el-checkbox v-model="formData.U_Enable"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="第三方登录:" prop="U_IsThird">
              <el-checkbox v-model="formData.U_IsThird"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4.8">
            <el-form-item label="是否只读:" prop="U_ReadOnly">
              <el-checkbox v-model="formData.U_ReadOnly"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="角色:">
          <el-select v-model="relevanceData" multiple @change="roleChange">
            <el-option v-for="item in allRoleData" :key="item.G_ID" :label="item.G_Name" :value="item.G_ID" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="职位:">
          <el-select v-model="relevanceData" multiple @change="roleChange">
            <el-option v-for="item in allRoleData" :key="item.G_ID" :label="item.G_Name" :value="item.G_ID" />
          </el-select>
        </el-form-item> -->
        <el-form-item class="remark" label="备注:" prop="Remark">
          <el-input v-model="formData.U_Remark" type="textarea" :autosize="{ minRows: 3 }"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting.visible = false">取消</el-button>
          <el-button type="primary" @click="handle"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改密码弹框 -->
    <el-dialog v-model="dialogSetting2.visible" :title="dialogSetting2.title" width="40%" draggable>
      <el-form label-width="120px" :model="formData2" :rules="rules2" ref="formRef2">
        <el-form-item label="当前用户:" prop="userName"> <el-input v-model="formData2.userName" /> </el-form-item>
        <el-form-item label="新密码:" prop="newPassword">
          <el-input v-model="formData2.newPassword" show-password type="password" />
        </el-form-item>
        <el-form-item label="确认新密码:" prop="affirmNewPassword">
          <el-input v-model="formData2.affirmNewPassword" show-password type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogSetting2.visible = false">取消</el-button>
          <el-button type="primary" @click="handle2"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 账号信息抽屉 -->
    <el-drawer v-model="isShowDrawer" :size="loginList.length ? 723 : 463" title="账户信息">
      <div class="user-content">
        <div class="avator">
          <el-image style="width: 100px; height: 100px" :src="getImagePath()" fit="contain" />
        </div>
        <el-card>
          <template #header>
            <div class="card-header">
              <h4>基本信息：</h4>
            </div>
          </template>
          <div class="item-child">用户名：{{ accountInfo.U_Name ? accountInfo.U_Name : "--" }}</div>
          <div class="item-child">员工名：{{ accountInfo.U_CName ? accountInfo.U_CName : "--" }}</div>
          <div class="item-child">绑定IP：{{ accountInfo.U_Binding_IP ? accountInfo.U_Binding_IP : "--" }}</div>
          <div class="item-child">绑定Mac： {{ accountInfo.U_Binding_MAC ? accountInfo.U_Binding_MAC : "--" }}</div>
          <div class="item-child">用户邮箱：{{ accountInfo.U_Email ? accountInfo.U_Email : "--" }}</div>
          <div class="item-child">是否启用：{{ accountInfo.U_Enable ? "是" : "否" }}</div>
          <div class="item-child">首次登录：{{ accountInfo.U_FirstLogin ? "是" : "否" }}</div>
          <div class="item-child">登录IP：{{ accountInfo.Log_IP ? accountInfo.Log_IP : "--" }}</div>
          <div class="item-child">管理员：{{ accountInfo.U_IsAdministrator ? "是" : "否" }}</div>
          <div class="item-child">超级管理员：{{ accountInfo.U_IsSuperAdministrator ? "是" : "否" }}</div>
          <div class="item-child">是否在线：{{ accountInfo.U_Online ? "是" : "否" }}</div>
          <div class="item-child">是否只读：{{ accountInfo.U_ReadOnly ? "是" : "否" }}</div>
          <div class="item-child">用户IP：{{ accountInfo.U_IP ? accountInfo.U_IP : "--" }}</div>
          <div class="item-child">用户ID：{{ accountInfo.U_ID ? accountInfo.U_ID : "--" }}</div>
          <div class="item-child">有效时间：{{ accountInfo.U_Validity_Time ? accountInfo.U_Validity_Time : "--" }}</div>
          <div class="item-child">上一次登录时间：{{ accountInfo.U_LastLogin_Time ? accountInfo.U_LastLogin_Time : "--" }}</div>
          <div class="item-child">
            上一次更改密码时间：{{ accountInfo.U_LastUpdatePasswordTime ? accountInfo.U_LastUpdatePasswordTime : "--" }}
          </div>
        </el-card>
      </div>
      <div v-if="loginList.length" class="right">
        <el-timeline>
          <el-timeline-item v-for="(item, index) in loginList" :key="index" :timestamp="item.time">
            {{ item.content }}
          </el-timeline-item>
        </el-timeline>
        <div class="page">
          <el-pagination
            v-model:current-page="currentPage"
            :pager-count="4"
            :page-size="20"
            layout="prev, pager, next"
            :total="loginListCount"
            small
            @current-change="getList"
          />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="tsx" name="accountManage">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import md5 from "js-md5";
import dayjs from "dayjs";
import { getRoleList, getRoleByUserId, saveRole } from "./index";
import useCurrentInstance from "@/utils/useCurrentInstance";
import avatarImage from "@/assets/images/avatar.gif";

const { proxy } = useCurrentInstance();
// 按钮状态
const BtnStatus = ref([false, true, true, true]);
// 单击保存对象
const clickObj = ref();
// 当前页
const currentPage = ref<number>(1);
// 表格配置
const tableSetting = reactive({
  columns: [
    { title: "顺序号", field: "U_Order", sortable: true, width: 90 },
    { title: "用户名", field: "U_Name", sortable: true },
    {
      title: "角色名",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [
            <div>
              {row.role.map((item: { G_Name: string }) => {
                return <el-tag style="margin-right:5px">{item.G_Name}</el-tag>;
              })}
            </div>
          ];
        }
      }
    },
    { title: "员工名字", field: "U_CName", sortable: true },
    {
      title: "管理员",
      field: "U_IsAdministrator",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.U_IsAdministrator} />];
        }
      }
    },
    {
      title: "超级管理员",
      field: "U_IsSuperAdministrator",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.U_IsSuperAdministrator} />];
        }
      }
    },
    {
      title: "启用状态",
      field: "U_Enable",
      sortable: true,
      slots: {
        default: ({ row }: any) => {
          return [<el-checkbox disabled v-model={row.U_Enable} />];
        }
      }
    },
    { title: "备注", field: "U_Remark", sortable: true },
    {
      title: "操作",
      width: 80,
      slots: {
        default: ({ row }: any) => {
          return (
            <el-button type="primary" link onClick={() => showDetails(row)}>
              查看
            </el-button>
          );
        }
      }
    }
  ],
  data: [] as any[]
});
// 所有用户数据
const allUserList = ref<any[]>([]);
// 所有角色数据
const allRoleData = ref<any[]>([]);
// 关联角色数据
const relevanceData = ref<any[]>([]);
// 账户信息
const accountInfo = ref<any>({});
// 登录数据总数
const loginListCount = ref<number>(0);
// 搜索条件
const searchVal = ref();
// 弹出框配置
const dialogSetting = reactive({
  visible: false,
  title: ""
});
// 修改密码弹出框配置
const dialogSetting2 = reactive({
  visible: false,
  title: "修改密码"
});
// 登录时间轴数据
const loginList = ref<any>([]);
// 是否展示抽屉
const isShowDrawer = ref<boolean>(false);
// 确认密码
const checkConfirmPassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback("请输入确认密码");
  }
  if (value != formData2.newPassword) {
    return callback("两次密码输入不一致，请重新输入");
  }
  return callback();
};
// 动态添加图片
const getImagePath = () => {
  if (accountInfo.value.U_Picture) {
    return import.meta.env.VITE_STATIC + accountInfo.value.U_Picture;
  }
  return avatarImage;
};
// 修改密码表单规则
const rules2 = reactive({
  userName: [{ required: true, message: "请填写当前用户", trigger: "blur" }],
  newPassword: [{ required: true, message: "请填写新密码!", trigger: "blur" }],
  affirmNewPassword: [{ required: true, validator: checkConfirmPassword, trigger: "blur" }]
});
// 修改密码表单绑定字段
const formData2 = reactive({
  newPassword: "",
  affirmNewPassword: "",
  userName: ""
});
// 表单绑定字段
const formData = ref({
  U_Order: 1,
  U_Name: "",
  U_PWD: "",
  U_IsThird: false,
  U_CName: "",
  U_IsAdministrator: true,
  U_IsSuperAdministrator: false,
  U_Enable: true,
  U_Remark: "",
  U_Validity_Time: "",
  U_PasswordErrCount: 0,
  U_ReadOnly: false,
  U_Binding_MAC: "",
  U_Binding_IP: "",
  U_Email: "",
  U_Mobile_Num: "",
  U_CertPath: "",
  U_Office_Phone: ""
});
// 表单规则
const rules = reactive<FormRules>({
  U_Order: [{ required: true, message: "请填写顺序号!", trigger: "blur" }],
  U_Name: [{ required: true, message: "请填写用户名!", trigger: "blur" }],
  U_CName: [{ required: true, message: "请填写员工名称!", trigger: "blur" }],
  U_PWD: [{ required: true, message: "请填写密码!", trigger: "blur" }]
});
// 表单实例
const formRef = ref<FormInstance>();
// 修改密码表单实例
const formRef2 = ref<FormInstance>();

// 获取表格数据
const getTableData = async () => {
  proxy.$showLoading();
  allRoleData.value = await getRoleList(); // 获取角色选项数组list
  const res = await proxy.$vueAxios.get("MasterBaseUsers/Get", {}, { noLoading: true }); // 所有用户数据
  const groupUsers = await proxy.$vueAxios.get("Master_Base_Group_User/Get", { order: "gU_ID des" }, { noLoading: true });
  for (let i = 0; i < res.List.length; i++) {
    const ids = groupUsers.List.filter((v: any) => v.U_ID == res.List[i].U_ID).map((j: any) => j.G_ID);
    const role = allRoleData.value.filter(v => ids.includes(v.G_ID));
    res.List[i].role = role;
  }
  tableSetting.data = res.List.sort((a: any, b: any) => a.U_Order - b.U_Order);
  allUserList.value = [...res.List];
  proxy.$hideLoading();
};
// 输入关键字进行搜索查询
const onSearchChange = (val: string) => {
  if (val) {
    tableSetting.data = allUserList.value.filter(
      (v: any) =>
        v.U_Name.toLowerCase().includes(val.toLowerCase().trim()) || v.U_CName.toLowerCase().includes(val.toLowerCase().trim())
    );
  } else {
    tableSetting.data = [...allUserList.value];
  }
};
// 新增或编辑中角色选择触发按钮
const roleChange = (values: any[]) => {
  relevanceData.value = values;
};
// 表格单击事件
const rowClick = ({ row }: any) => {
  clickObj.value = row;
  BtnStatus.value[1] = false;
  BtnStatus.value[2] = false;
  BtnStatus.value[3] = false;
};

// 点击“查看”详情
const showDetails = (row: any) => {
  getLogData(row.U_ID);
  accountInfo.value = row;
  isShowDrawer.value = true;
};

const getDateRange = (daysAgo: number = 10) => {
  const endTime = new Date(); // 当前日期
  const startTime = new Date();
  startTime.setDate(endTime.getDate() - daysAgo); // 往前推指定天数

  const formatDate = (date: any) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份补零
    const day = String(date.getDate()).padStart(2, "0"); // 日期补零
    return `${year}/${month}/${day}`;
  };

  return {
    startTime: formatDate(startTime),
    endTime: formatDate(endTime)
  };
};

// 登录日志翻页
const getList = (val: any) => {
  currentPage.value = val;
  getLogData(accountInfo.value.U_ID);
};
// 获取登录信息
const { startTime, endTime } = getDateRange(10);
const getLogData = (id: string) => {
  proxy.$vueAxios
    .get("MasterBaseLog/getList", {
      uId: id,
      startTime: startTime,
      endTime: endTime,
      keyword: "",
      isHighRisk: "",
      pageIndex: currentPage.value,
      pageSize: 12
    })
    .then((res: any) => {
      loginList.value = [];
      res.List.forEach((item: any) => {
        loginList.value.push({
          content: "登录",
          time: item.Log_Time
        });
      });
      loginListCount.value = res.Count;
    });
};
// 新增
const add = () => {
  relevanceData.value = [];
  dialogSetting.visible = true;
  dialogSetting.title = "新增";
  formRef.value?.resetFields();
};
// 修改
const edit = async () => {
  dialogSetting.visible = true;
  dialogSetting.title = "修改";
  nextTick(() => {
    formData.value.U_CName = clickObj.value.U_CName;
    formData.value.U_Enable = clickObj.value.U_Enable;
    formData.value.U_IsAdministrator = clickObj.value.U_IsAdministrator;
    formData.value.U_IsSuperAdministrator = clickObj.value.U_IsSuperAdministrator;
    formData.value.U_IsThird = clickObj.value.U_IsThird;
    formData.value.U_Name = clickObj.value.U_Name;
    formData.value.U_Order = clickObj.value.U_Order;
    formData.value.U_Remark = clickObj.value.U_Remark;
    formData.value.U_Validity_Time = clickObj.value.U_Validity_Time;
    formData.value.U_PasswordErrCount = clickObj.value.U_PasswordErrCount;
    formData.value.U_ReadOnly = clickObj.value.U_ReadOnly;
    // formData.value.U_PWD = clickObj.value.U_PWD;

    formData.value.U_Binding_MAC = clickObj.value.U_Binding_MAC;
    formData.value.U_Binding_IP = clickObj.value.U_Binding_IP;
    formData.value.U_Email = clickObj.value.U_Email;
    formData.value.U_Mobile_Num = clickObj.value.U_Mobile_Num;
    formData.value.U_CertPath = clickObj.value.U_CertPath;
    formData.value.U_Office_Phone = clickObj.value.U_Office_Phone;
  });

  await getRoleByUserId(clickObj.value.U_ID).then(res => {
    relevanceData.value = res;
  });
};
// 删除
const del = () => {
  proxy.$messageBox
    .confirm("确定删除该数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(() => {
      proxy.$vueAxios.post("MasterBaseUsers/Delete", [clickObj.value.U_ID]).then((res: any) => {
        if (res.Mark) {
          tableSetting.data = tableSetting.data.filter(
            (v: any) => v !== tableSetting.data.find((v: any) => v.U_ID === clickObj.value.U_ID)
          );
          proxy.$message.success("删除成功");
        } else {
          proxy.$message.error("请先删除角色!");
        }
      });
    })
    .catch(err => {
      console.log(err);
      proxy.$message("取消删除");
    });
};
// 确认
const handle = () => {
  formRef.value!.validate((isValid: boolean) => {
    if (isValid) {
      if (dialogSetting.title === "新增") {
        const U_ID = proxy.$global.createID();
        proxy.$vueAxios
          .post(
            "MasterBaseUsers",
            {
              u_ID: U_ID,
              u_Name: formData.value.U_Name,
              u_CName: formData.value.U_CName,
              u_Enable: formData.value.U_Enable,
              u_IsThird: formData.value.U_IsThird,
              u_Remark: formData.value.U_Remark,
              u_Order: formData.value.U_Order,
              // u_PWD: md5(formData.value.U_PWD),
              u_IsAdministrator: formData.value.U_IsAdministrator,
              u_IsSuperAdministrator: formData.value.U_IsSuperAdministrator,
              u_Validity_Time: dayjs(formData.value.U_Validity_Time).format("YYYY-MM-DD"),
              u_ReadOnly: formData.value.U_ReadOnly,

              u_Binding_MAC: formData.value.U_Binding_MAC,
              u_Binding_IP: formData.value.U_Binding_IP,
              u_Email: formData.value.U_Email,
              u_Mobile_Num: formData.value.U_Mobile_Num,
              u_CertPath: formData.value.U_CertPath,
              u_Office_Phone: formData.value.U_Office_Phone
            },
            { noLoading: true }
          )
          .then(async () => {
            dialogSetting.visible = false;
            await saveRole(relevanceData.value, U_ID);
            getTableData(); //重新获取表格数据
          });
      } else {
        proxy.$vueAxios
          .post(
            "MasterBaseUsers/Update",
            {
              u_ID: clickObj.value.U_ID,
              u_Name: formData.value.U_Name,
              u_CName: formData.value.U_CName,
              u_Enable: formData.value.U_Enable,
              u_IsThird: formData.value.U_IsThird,
              u_Remark: formData.value.U_Remark,
              u_Order: formData.value.U_Order,
              u_IsAdministrator: formData.value.U_IsAdministrator,
              u_IsSuperAdministrator: formData.value.U_IsSuperAdministrator,
              u_Validity_Time: formData.value.U_Validity_Time ? dayjs(formData.value.U_Validity_Time).format("YYYY-MM-DD") : null,
              u_PasswordErrCount: formData.value.U_PasswordErrCount,
              u_ReadOnly: formData.value.U_ReadOnly,

              u_Binding_MAC: formData.value.U_Binding_MAC,
              u_Binding_IP: formData.value.U_Binding_IP,
              u_Email: formData.value.U_Email,
              u_Mobile_Num: formData.value.U_Mobile_Num,
              u_CertPath: formData.value.U_CertPath,
              u_Office_Phone: formData.value.U_Office_Phone
            },
            { noLoading: true }
          )
          .then(async () => {
            dialogSetting.visible = false;
            await saveRole(relevanceData.value, clickObj.value.U_ID);
            getTableData();
          });
      }
    }
  });
};
// 修改密码
const updataPWD = () => {
  formData2.userName = clickObj.value.U_Name;
  dialogSetting2.visible = true;
};
// 修改密码确认事件
const handle2 = () => {
  formRef2.value!.validate((isValid: boolean) => {
    if (isValid) {
      proxy.$vueAxios
        .post(
          "MasterBaseUsers/ChangePassword",
          {
            u_Name: formData2.userName,
            newPassword: md5(formData2.newPassword)
          },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            dialogSetting2.visible = false;
            proxy.$message.success("密码修改成功！");
          }
        });
    }
  });
};
onMounted(() => {
  getTableData();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
.line {
  display: flex;
  .el-form-item {
    width: 50%;
  }
}
.check-group {
  justify-content: space-between;
}
.remark {
  margin-bottom: 0;
}
:deep(.el-dialog__body) {
  padding: 14px 20px 12px;
}
:deep(.el-drawer__body) {
  display: flex;
}
:deep(.el-timeline) {
  padding-left: 12px;
}
.user-content {
  width: 463px;
  line-height: 30px;
  .avator {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px 0 40px;
    .el-image {
      border-radius: 50%;
    }
  }
  h4 {
    margin: 0;
  }
  :deep(.el-card__header) {
    padding: 10px;
  }
  :deep(.el-card__body) {
    padding: 10px;
  }
  .item {
    display: flex;
    justify-content: space-between;
    .item-child {
      width: 48%;
    }
  }
}
.right {
  display: flex;
  flex-direction: column;
  width: 260px;
}
</style>
